<?php
// =========百度第三方登陆接口=============
$baidu = new baidu();
if( !isset($_GET['code']) ){
        echo $baidu->index(); 
}else{
    $array = $baidu->baidu($_GET['code']);
    echo '<pre>';
    print_r($array);
}
class baidu{
	private $apikey,$secretkey,$redirect_uri,$img,$scope;
	// 百度登陆的配置。
	public function __construct(){
          $this->apikey = "";
          $this->secretkey = "";
          $this->redirect_uri = "http://www.useryx.net";
          $this->img = "/Public/baidu.png"; // 图片
	}
	// 登陆图片和url，返回连接
	public function index(){
    		$redirect_url = urlencode($this->redirect_uri);
    		$url = "https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=$this->apikey&redirect_uri=$redirect_url";
            return "<a href='$url'><img src='$this->img' alt='百度登陆'></a>";
	}
    // 返回数据。
    public function baidu($code){
        $client_id = $this->apikey;
        $client_secret = $this->secretkey;
        $redirect_uri = urlencode($this->redirect_uri);
        // 获取access_token
        $url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code=$code&client_id=$client_id&client_secret=$client_secret&redirect_uri=$redirect_uri";
        $arr =  json_decode(file_get_contents($url),true);
       $access_token = $arr['access_token'];
       // 获取信息
       $url = "https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser?access_token=$access_token";
       $array = $this->http_request($url);
       $array = json_decode($array,true);
       return array($arr,$array);
    }
    // post 发送数据
    private function http_request($url, $data = null){  
        $curl = curl_init();  
        curl_setopt($curl, CURLOPT_URL, $url);  
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);  
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);  
        if (!empty($data)){  
            curl_setopt($curl, CURLOPT_POST, 1);  
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  
        }  
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
        $output = curl_exec($curl);  
        curl_close($curl);  
        return $output;  
	}  
}